package sri.proiect.search;

import java.io.File;
import java.io.IOException;
import java.util.List;

import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.analysis.standard.StandardAnalyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.ScoreDoc;
import org.apache.lucene.search.TopScoreDocCollector;
import org.apache.lucene.store.FSDirectory;
import org.apache.lucene.util.Version;

import sri.proiect.index.DatabaseIndexManager;
import sri.proiect.models.Hotel;
import sri.proiect.utils.DBColumn;

public class AbstractSearcher {
	
	protected static DatabaseIndexManager indexManager = new DatabaseIndexManager();
    protected Analyzer analyzer =  new StandardAnalyzer(Version.LUCENE_CURRENT);;
    
    protected boolean ckeckOrCreateIndex() {
    	if(false == indexManager.ifIndexExist()){
    		try {
				if(false == indexManager.createIndex()){
					return false;
				}
			} catch (IOException e) {
				e.printStackTrace();
				return false;
			}
    	}
    	return true;
    }
    
    protected IndexSearcher getIndexSearcher() {
		IndexSearcher indexSearcher = null;
    	FSDirectory dir;
    	
    	try{
    		dir = FSDirectory.open(new File(indexManager.getIndexDir()));
    		indexSearcher = new IndexSearcher(dir);
    	}catch(IOException ioe){
    		ioe.printStackTrace();
    	}
		return indexSearcher;
	}
    
    protected void searchForHotels(List<Hotel> searchResult, Query query) {
		try {
			TopScoreDocCollector collector = TopScoreDocCollector.create(10, true);
			IndexSearcher indexSearcher = getIndexSearcher();
		    indexSearcher.search(query, collector);

		    ScoreDoc[] hits = collector.topDocs().scoreDocs;
			
			//Hits hits = indexSearcher.search(query);
			for(int i = 0; i < hits.length; i ++){
				int docId = hits[i].doc;
			      Document d = indexSearcher.doc(docId);
				
				Hotel hotel = extractHotelFromSearchResult(d);
				
				searchResult.add(hotel);
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	private Hotel extractHotelFromSearchResult(Document d) {
		Hotel hotel = new Hotel();
		hotel.setNume(d.get(DBColumn.Nume_Hotel.getName()));
		hotel.setOras(d.get(DBColumn.Oras.getName()));
		hotel.setJudet(d.get(DBColumn.Judet.getName()));
		hotel.setLink(d.get(DBColumn.Link.getName()));
		if (d.get(DBColumn.NrStele.getName()) != null) {
			hotel.setNrStele(Integer.parseInt(d.get(DBColumn.NrStele.getName())));
		}
		hotel.setHits(3);
		hotel.setTelefon(d.get(DBColumn.Telefon.getName()));
		hotel.setShortDescription(d.get(DBColumn.Detalii.getName()));
		hotel.setEmail(d.get(DBColumn.Email.getName()));
		hotel.setAdresa(d.get(DBColumn.Adresa.getName()));
		hotel.setWebsite(d.get(DBColumn.Website.getName()));
		return hotel;
	}
}
